﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PLC_Master
{
    public partial class FormMain : Form
    {
        private PLCMaster _plcMaster { get; set; }

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            _plcMaster = PLCMaster.GetInstance();
            MainWorkThread();
        }

        private void MainWorkThread()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    if (_plcMaster.Connected)
                    {
                        try
                        {
                            PLCStatus status = _plcMaster.ReadStatus();
                            ChangeStatus(status);
                        }
                        catch (Exception)
                        {
                            _plcMaster.Disconnect();
                        }
                    }

                    Thread.Sleep(300);
                }
            });
        }

        private void ChangeStatus(PLCStatus status)
        {
            this.Invoke(new Action(() =>
            {
                panelInput.BackColor = status.IsEmergencyStop ? Color.Red : Color.Blue;
            }));
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string IP = this.txtIP.Text.Trim();
            int Port = (int)this.numPort.Value;

            try
            {
                bool bRet = _plcMaster.Connect(IP, Port);
                if (bRet)
                {
                    ChangeControlEnabled(true);
                    Debug.WriteLine("连接成功");
                }
                else
                {
                    Debug.WriteLine("连接Fail");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            _plcMaster.Disconnect();
            ChangeControlEnabled(false);
        }

        private void ChangeControlEnabled(bool isConnected)
        {
            this.btnConnect.Enabled = !isConnected;
            this.btnDisconnect.Enabled = isConnected;
            this.panelMain.Enabled = isConnected;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if(_plcMaster.Connected)
            {
                _plcMaster.StartTest();
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (_plcMaster.Connected)
            {
                _plcMaster.StopTest();
            }
        }
    }
}
